<!DOCTYPE HTML>
<html lang="zh-CN">


<head><meta name="generator" content="Hexo 3.8.0">
    <meta charset="utf-8">
    <meta name="keywords" content="【计算机网络】TCP、UDP通信总结, ZhengN_Blog">
    <meta name="description" content="一、什么是socket？Socket的英文原义是“孔”或“插座”。在编程中，Socket被称做套接字，是网络通信中的一种约定。Socket编程的应用无处不在，我们平时用的QQ、微信、浏览器等程序，都与Socket编程有关。我们平时使用浏览器">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>【计算机网络】TCP、UDP通信总结 | ZhengN_Blog</title>
    <link rel="icon" type="image/jpeg" href="/favicon.jpg">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">
    <style type="text/css">
        
    </style>

    <script src="/libs/jquery/jquery-2.2.0.min.js"></script>
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>


<body>

<header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">ZhengN_Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fa fa-navicon"></i></a>
<ul class="right">
    
    <li class="hide-on-med-and-down">
        <a href="/" class="waves-effect waves-light">
            
            <i class="fa fa-home"></i>
            
            <span>首页</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/tags" class="waves-effect waves-light">
            
            <i class="fa fa-tags"></i>
            
            <span>标签</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/categories" class="waves-effect waves-light">
            
            <i class="fa fa-bookmark"></i>
            
            <span>分类</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/archives" class="waves-effect waves-light">
            
            <i class="fa fa-archive"></i>
            
            <span>归档</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/about" class="waves-effect waves-light">
            
            <i class="fa fa-user-circle-o"></i>
            
            <span>关于</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/friends" class="waves-effect waves-light">
            
            <i class="fa fa-address-book"></i>
            
            <span>友情链接</span>
        </a>
    </li>
    
    <li>
        <a href="#searchModal" class="modal-trigger waves-effect waves-light">
            <i id="searchIcon" class="fa fa-search" title="搜索"></i>
        </a>
    </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">ZhengN_Blog</div>
        <div class="logo-desc">
            
            printf(&#34;每天进步一点点~&#34;);
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li>
            <a href="/" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-home"></i>
                
                首页
            </a>
        </li>
        
        <li>
            <a href="/tags" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-tags"></i>
                
                标签
            </a>
        </li>
        
        <li>
            <a href="/categories" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-bookmark"></i>
                
                分类
            </a>
        </li>
        
        <li>
            <a href="/archives" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-archive"></i>
                
                归档
            </a>
        </li>
        
        <li>
            <a href="/about" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-user-circle-o"></i>
                
                关于
            </a>
        </li>
        
        <li>
            <a href="/friends" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-address-book"></i>
                
                友情链接
            </a>
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/zhengnianli/stm32_weather" class="waves-effect waves-light" target="_blank">
                <i class="fa fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>

        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/zhengnianli/stm32_weather" class="github-corner tooltipped hide-on-med-and-down" target="_blank" data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewbox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/>
    </svg>
</a>
        
    </nav>

</header>





<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/6.jpg')">
    <div class="container">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        【计算机网络】TCP、UDP通信总结
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>



<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 20px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/socket/" target="_blank">
                                <span class="chip bg-color">socket</span>
                            </a>
                        
                            <a href="/tags/网络编程/" target="_blank">
                                <span class="chip bg-color">网络编程</span>
                            </a>
                        
                            <a href="/tags/TCP/" target="_blank">
                                <span class="chip bg-color">TCP</span>
                            </a>
                        
                            <a href="/tags/UDP/" target="_blank">
                                <span class="chip bg-color">UDP</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fa fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/计算机网络/" class="post-category" target="_blank">
                                计算机网络
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                <div class="post-date info-break-policy">
                    <i class="fa fa-calendar-minus-o fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2019-06-30
                </div>

                
                    
                    <div class="info-break-policy">
                        <i class="fa fa-file-word-o fa-fw"></i>文章字数:&nbsp;&nbsp;
                        5.8k
                    </div>
                    

                    
                    <div class="info-break-policy">
                        <i class="fa fa-clock-o fa-fw"></i>阅读时长:&nbsp;&nbsp;
                        24 分
                    </div>
                    
                
				
				
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="fa fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="一、什么是socket？"><a href="#一、什么是socket？" class="headerlink" title="一、什么是socket？"></a>一、什么是socket？</h2><p>Socket的英文原义是“孔”或“插座”。在编程中，Socket被称做<code>套接字</code>，是网络通信中的一种约定。Socket编程的应用无处不在，我们平时用的QQ、微信、浏览器等程序，都与Socket编程有关。我们平时使用浏览器查资料，这个过程的技术原理是怎样的呢？</p>
<img src="https://s2.ax1x.com/2019/07/01/Z3XNyn.png" alt border="0" width="350">



<p>我们平时使用浏览器，大致就是这样的一个过程。这里有两个重要的名词：<code>服务端</code>与<code>客户端</code>。</p>
<p>Socket编程的目的就是如何实现这两端之间的通信。</p>
<h3 id="1、Socket编程在嵌入式中也很重要"><a href="#1、Socket编程在嵌入式中也很重要" class="headerlink" title="1、Socket编程在嵌入式中也很重要"></a>1、Socket编程在嵌入式中也很重要</h3><p>Socket编程不仅仅在互联网方面很重要，在我们的嵌入式方面也是非常的重要，因为现在很多电子设备都趋向于联网。比如很多嵌入式工作的招聘要求都会有这一条要求：</p>
<p><img src="https://s2.ax1x.com/2019/06/30/Z1Kytg.png" alt></p>
<p><img src="https://s2.ax1x.com/2019/06/30/Z1KoAU.png" alt></p>
<p>说一点题外话，还在学校的朋友，如果感觉到很迷茫，不知道学什么的时候，可以上招聘网站上看看自己未来工作相关的职位的任职要求，这样就可以总结自己的一些不足、比较有针对性的去学习。</p>
<h2 id="二、Socket编程中的几个重要概念"><a href="#二、Socket编程中的几个重要概念" class="headerlink" title="二、Socket编程中的几个重要概念"></a>二、Socket编程中的几个重要概念</h2><p>Socket编程用于解决我们<code>客户端</code>与<code>服务端</code>之间通信的问题。我们平时多多少少都有听过IP地址、端口、TCP协议、UDP协议等概念，这些都与Socket编程中相关，想要知道怎么用起来，当然得先了解它们的一些介绍。下面看一下这些专业术语的一些要点介绍：</p>
<h3 id="1、什么是IP地址？"><a href="#1、什么是IP地址？" class="headerlink" title="1、什么是IP地址？"></a>1、什么是IP地址？</h3><p><code>IP地址（Internet Protocol Address）</code>是指互联网协议地址，又译为<code>网际协议地址</code>。IP地址被用来给Internet上的电脑一个编号。我们可以把“个人电脑”比作“一台电话”，那么“IP地址”就相当于“电话号码”。若计算机1知道计算机2的IP地址，则计算机1就能访问计算机2。</p>
<p>IP地址是一个32位的二进制数，通常被分割为4个“8位二进制数”（也就是4个字节）。IP地址通常用<code>点分十进制</code>表示成（a.b.c.d）的形式，其中，a,b,c,d都是0~255之间的十进制整数。例：点分十进IP地址（100.4.5.6），实际上是32位二进制数（01100100.00000100.00000101.00000110）。</p>
<p>IP地址有<code>IPv4</code>与<code>IPv6</code>之分，现在用得较多的是IPv4。其中，有一个特殊的IP地址需要我们记住：<code>127.0.0.1</code>，这是回送地址，即本地机，一般用来测试使用。后边我们的实例中会用到。</p>
<p>关于IP地址还有很多知识要点，但是对于在Socket编程中的应用，我们暂且知道这么多就可以。</p>
<h3 id="2、什么是TCP-IP端口？"><a href="#2、什么是TCP-IP端口？" class="headerlink" title="2、什么是TCP/IP端口？"></a>2、什么是TCP/IP端口？</h3><p>上一点中我们提到，若计算机1知道计算机2的IP地址，则计算机1就能访问计算机2。但是，我们要访问计算机2中的不同的应用软件，则还得需要一个信息：<code>端口</code>。端口使用16bit进行编号，即其范围为：<code>0~65536</code>。但<code>0~1023</code> 的端口一般由系统分配给特定的服务程序，例如 Web 服务的端口号为 80，FTP 服务的端口号为 21等。</p>
<h3 id="3、什么是协议？"><a href="#3、什么是协议？" class="headerlink" title="3、什么是协议？"></a>3、什么是协议？</h3><p>协议（Protocol）是通信双方进行数据交互的一种约定。如TCP、UDP协议：</p>
<h4 id="（1）TCP协议"><a href="#（1）TCP协议" class="headerlink" title="（1）TCP协议"></a>（1）TCP协议</h4><p>TCP（Transmission Control Protocol 传输控制协议）是一种面向连接的、可靠的、基于字节流的传输层通信协议，数据可以准确发送，数据丢失会重发。TCP协议常用于web应用中。</p>
<h5 id="TCP连接（三次握手）"><a href="#TCP连接（三次握手）" class="headerlink" title="TCP连接（三次握手）"></a>TCP连接（三次握手）</h5><p>TCP传输起始时，客户端、服务端要完成三次数据交互工作才能建立连接，常称为<strong>三次握手</strong>。可形象比喻为如下对话：</p>
<blockquote>
<p>客户端：服务端您好，我有数据要发给你，请求您开通访问权限。</p>
<p>服务端：客户端您好，已给您开通权限，您可以发送数据了。</p>
<p>客户端：收到，谢谢。</p>
</blockquote>
<p>具体示意图为：</p>
<p><img src="https://s2.ax1x.com/2019/06/30/Z1UacT.png" alt></p>
<p>这里的SYN和ACK是都是标志位，其中SYN代表新建一个连接，ACK代表确认。其中m、n都是随机数。具体说明如：</p>
<ul>
<li>第一次握手：SYN标志位被置位，客户端向服务端发送一个随机数m。</li>
<li>第二次握手：ACK、SYN标志位被置位。服务端向客户端发送m+1表示确认刚才收到的数据，同时向客户端发送一个随机数n。</li>
<li>第三次握手：ACK标志被置位。客户端向服务端发送n+1表示确认收到数据。</li>
</ul>
<h5 id="TCP断开（四次挥手）"><a href="#TCP断开（四次挥手）" class="headerlink" title="TCP断开（四次挥手）"></a>TCP断开（四次挥手）</h5><p>TCP断开连接时，客户端、服务端要完成四次数据交互工作才能建立连接，常称为<strong>四次挥手</strong>。可形象比喻为如下对话：</p>
<blockquote>
<p>客户端：服务端您好，我发送数据完毕了，即将和您断开连接。</p>
<p>服务端：客户端您好，我稍稍准备一下，再给您断开</p>
<p>服务端：客户端您好，我准备好了，您可以断开连接了。</p>
<p>客户端：好的，合作愉快！</p>
</blockquote>
<p>具体示意图为：</p>
<p><img src="https://s2.ax1x.com/2019/06/30/Z1dxts.png" alt></p>
<p>这里的FIN也是一个标志位，代表断开连接。具体说明类似<strong>三次握手</strong>。</p>
<p><strong>为什么建立连接只需要三次数据交互，而断开连接需要四次呢？</strong></p>
<p>建立连接时，服务端在监听状态下，收到建立连接请求的SYN报文后，把ACK和SYN放在一个报文里发送给客户端。</p>
<p>而关闭连接时，当收到对方的FIN报文时，仅仅表示对方不再发送数据了但是还能接收数据，己方也未必全部数据都发送给对方了，所以己方可以立即close，也可以发送一些数据给对方后，再发送FIN报文给对方来表示同意现在关闭连接，因此，己方ACK和FIN一般都会分开发送。</p>
<h4 id="（2）UDP协议"><a href="#（2）UDP协议" class="headerlink" title="（2）UDP协议"></a>（2）UDP协议</h4><p>UDP（User Datagram Protocol， 用户数据报协议）是一种无连接的传输层协议，提供面向事务的简单不可靠信息传送服务，可以保证通讯效率，传输延时小。例如视频聊天应用中用的就是UDP协议，这样可以保证及时丢失少量数据，视频的显示也不受很大影响。</p>
<h3 id="4、什么是协议族？"><a href="#4、什么是协议族？" class="headerlink" title="4、什么是协议族？"></a>4、什么是协议族？</h3><p>协议族是多个协议的统称。比如我们的TCP/IP协议族，其不仅仅是TCP协议、IP协议，而是多个协议的集合，其包含IP、TCP、UDP、FTP、SMTP等协议。</p>
<h2 id="三、socket编程的API接口"><a href="#三、socket编程的API接口" class="headerlink" title="三、socket编程的API接口"></a>三、socket编程的API接口</h2><h3 id="1、Linux下的socket-API接口"><a href="#1、Linux下的socket-API接口" class="headerlink" title="1、Linux下的socket API接口"></a>1、Linux下的socket API接口</h3><h4 id="（1）创建socket：socket-函数"><a href="#（1）创建socket：socket-函数" class="headerlink" title="（1）创建socket：socket()函数"></a>（1）创建socket：socket()函数</h4><p><strong>函数原型：</strong></p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">int</span> <span class="token function">socket</span><span class="token punctuation">(</span><span class="token keyword">int</span> af<span class="token punctuation">,</span> <span class="token keyword">int</span> type<span class="token punctuation">,</span> <span class="token keyword">int</span> protocol<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<ul>
<li>af参数：af 为地址族（Address Family），也就是 IP 地址类型，常用的有 AF_INET 和 AF_INET6，其前缀也可以是PF（Protocol  Family），即PF_INET 和 PF_INET6。</li>
<li>type参数：type 为数据传输方式，常用的有 面向连接（<code>SOCK_STREAM</code>）方式（即TCP） 和 无连接（<code>SOCK_DGRAM</code>）的方式（即UDP）。</li>
<li>protocol参数：protocol 表示传输协议，常用的有 <code>IPPROTO_TCP</code> 和 <code>IPPTOTO_UDP</code>，分别表示 TCP 传输协议和 UDP 传输协议。</li>
</ul>
<p><strong>使用示例：</strong></p>
<p>创建TCP套接字：</p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">int</span> tcp_socket <span class="token operator">=</span> <span class="token function">socket</span><span class="token punctuation">(</span>AF_INET<span class="token punctuation">,</span> SOCK_STREAM<span class="token punctuation">,</span> IPPROTO_TCP<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>创建UDP套接字：</p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">int</span> udp_socket <span class="token operator">=</span> <span class="token function">socket</span><span class="token punctuation">(</span>AF_INET<span class="token punctuation">,</span> SOCK_DGRAM<span class="token punctuation">,</span> IPPROTO_UDP<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<h4 id="（2）绑定套接字：bind-函数"><a href="#（2）绑定套接字：bind-函数" class="headerlink" title="（2）绑定套接字：bind()函数"></a>（2）绑定套接字：bind()函数</h4><p><strong>函数原型：</strong></p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">int</span> <span class="token function">bind</span><span class="token punctuation">(</span><span class="token keyword">int</span> sock<span class="token punctuation">,</span> <span class="token keyword">struct</span> sockaddr <span class="token operator">*</span>addr<span class="token punctuation">,</span> socklen_t addrlen<span class="token punctuation">)</span><span class="token punctuation">;</span> </code></pre>
<ul>
<li>sock参数：sock 为 socket 文件描述符。</li>
<li>addr参数：addr 为 sockaddr 结构体变量的指针。</li>
<li>addrlen参数：addrlen 为 addr 变量的大小，可由 sizeof() 计算得出。</li>
</ul>
<p><strong>使用示例：</strong></p>
<p>将创建的套接字<code>ServerSock</code>与本地IP<code>127.0.0.1</code>、端口<code>1314</code>进行绑定：</p>
<pre class=" language-c"><code class="language-c"><span class="token comment" spellcheck="true">/* 创建服务端socket */</span>
<span class="token keyword">int</span> ServerSock <span class="token operator">=</span> <span class="token function">socket</span><span class="token punctuation">(</span>PF_INET<span class="token punctuation">,</span> SOCK_STREAM<span class="token punctuation">,</span> IPPROTO_TCP<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment" spellcheck="true">/* 设置服务端信息 */</span>
<span class="token keyword">struct</span> sockaddr_in ServerSockAddr<span class="token punctuation">;</span>
<span class="token function">memset</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>ServerSockAddr<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>ServerSockAddr<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>     <span class="token comment" spellcheck="true">// 给结构体ServerSockAddr清零</span>
ServerSockAddr<span class="token punctuation">.</span>sin_family <span class="token operator">=</span> PF_INET<span class="token punctuation">;</span>                      <span class="token comment" spellcheck="true">// 使用IPv4地址</span>
ServerSockAddr<span class="token punctuation">.</span>sin_addr<span class="token punctuation">.</span>s_addr <span class="token operator">=</span> <span class="token function">inet_addr</span><span class="token punctuation">(</span><span class="token string">"127.0.0.1"</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment" spellcheck="true">// 本机IP地址</span>
ServerSockAddr<span class="token punctuation">.</span>sin_port <span class="token operator">=</span> <span class="token function">htons</span><span class="token punctuation">(</span><span class="token number">1314</span><span class="token punctuation">)</span><span class="token punctuation">;</span>                  <span class="token comment" spellcheck="true">// 端口</span>

<span class="token comment" spellcheck="true">/* 绑定套接字 */</span>
<span class="token function">bind</span><span class="token punctuation">(</span>ServerSock<span class="token punctuation">,</span> <span class="token punctuation">(</span>SOCKADDR<span class="token operator">*</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>ServerSockAddr<span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>SOCKADDR<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>其中<code>struct sockaddr_in</code>类型的结构体变量用于保存IPv4的IP信息。若是IPv6，则有对应的结构体：</p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">struct</span> sockaddr_in6 
<span class="token punctuation">{</span> 
    sa_family_t sin6_family<span class="token punctuation">;</span>    <span class="token comment" spellcheck="true">// 地址类型，取值为AF_INET6</span>
    in_port_t sin6_port<span class="token punctuation">;</span>         <span class="token comment" spellcheck="true">// 16位端口号</span>
    uint32_t sin6_flowinfo<span class="token punctuation">;</span>     <span class="token comment" spellcheck="true">// IPv6流信息</span>
    <span class="token keyword">struct</span> in6_addr sin6_addr<span class="token punctuation">;</span>  <span class="token comment" spellcheck="true">// 具体的IPv6地址</span>
    uint32_t sin6_scope_id<span class="token punctuation">;</span>     <span class="token comment" spellcheck="true">// 接口范围ID</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span></code></pre>
<h4 id="（3）建立连接：connect-函数"><a href="#（3）建立连接：connect-函数" class="headerlink" title="（3）建立连接：connect()函数"></a>（3）建立连接：connect()函数</h4><p><strong>函数原型：</strong></p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">int</span> <span class="token function">connect</span><span class="token punctuation">(</span><span class="token keyword">int</span> sock<span class="token punctuation">,</span> <span class="token keyword">struct</span> sockaddr <span class="token operator">*</span>serv_addr<span class="token punctuation">,</span> socklen_t addrlen<span class="token punctuation">)</span><span class="token punctuation">;</span>  </code></pre>
<p>参数与<code>bind()</code>的参数类似。</p>
<p><strong>使用示例：</strong></p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">int</span> ClientSock <span class="token operator">=</span> <span class="token function">socket</span><span class="token punctuation">(</span>AF_INET<span class="token punctuation">,</span> SOCK_STREAM<span class="token punctuation">,</span> IPPROTO_TCP<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">connect</span><span class="token punctuation">(</span>ClientSock<span class="token punctuation">,</span> <span class="token punctuation">(</span>SOCKADDR<span class="token operator">*</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>ServerSockAddr<span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>SOCKADDR<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<h4 id="（4）监听：listen-函数"><a href="#（4）监听：listen-函数" class="headerlink" title="（4）监听：listen()函数"></a>（4）监听：listen()函数</h4><p><strong>函数原型：</strong></p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">int</span> <span class="token function">listen</span><span class="token punctuation">(</span><span class="token keyword">int</span> sock<span class="token punctuation">,</span> <span class="token keyword">int</span> backlog<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<ul>
<li>sock参数：sock 为需要进入监听状态的套接字。</li>
<li>backlog参数：backlog 为请求队列的最大长度。</li>
</ul>
<p><strong>使用示例：</strong></p>
<pre class=" language-c"><code class="language-c"><span class="token comment" spellcheck="true">/* 进入监听状态 */</span>
<span class="token function">listen</span><span class="token punctuation">(</span>ServerSock<span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<h4 id="（5）接收请求：accept-函数"><a href="#（5）接收请求：accept-函数" class="headerlink" title="（5）接收请求：accept()函数"></a>（5）接收请求：accept()函数</h4><p><strong>函数原型：</strong></p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">int</span> <span class="token function">accept</span><span class="token punctuation">(</span><span class="token keyword">int</span> sock<span class="token punctuation">,</span> <span class="token keyword">struct</span> sockaddr <span class="token operator">*</span>addr<span class="token punctuation">,</span> socklen_t <span class="token operator">*</span>addrlen<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<ul>
<li>sock参数：sock 为服务器端套接字。</li>
<li>addr参数：addr 为 sockaddr_in 结构体变量。</li>
<li>addrlen参数：addrlen 为参数 addr 的长度，可由 sizeof() 求得。</li>
<li>返回值：一个新的套接字，用于与客户端通信。</li>
</ul>
<p><strong>使用示例：</strong></p>
<pre class=" language-c"><code class="language-c"><span class="token comment" spellcheck="true">/* 监听客户端请求，accept函数返回一个新的套接字，发送和接收都是用这个套接字 */</span>
<span class="token keyword">int</span> ClientSock <span class="token operator">=</span> <span class="token function">accept</span><span class="token punctuation">(</span>ServerSock<span class="token punctuation">,</span> <span class="token punctuation">(</span>SOCKADDR<span class="token operator">*</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>ClientAddr<span class="token punctuation">,</span> <span class="token operator">&amp;</span>len<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<h4 id="（6）关闭：close-函数"><a href="#（6）关闭：close-函数" class="headerlink" title="（6）关闭：close()函数"></a>（6）关闭：close()函数</h4><p><strong>函数原型：</strong></p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">int</span> <span class="token function">close</span><span class="token punctuation">(</span><span class="token keyword">int</span> fd<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<ul>
<li>fd：要关闭的文件描述符。</li>
</ul>
<p><strong>使用示例：</strong></p>
<pre class=" language-c"><code class="language-c"><span class="token function">close</span><span class="token punctuation">(</span>ServerSock<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<h4 id="（7）数据的接收和发送"><a href="#（7）数据的接收和发送" class="headerlink" title="（7）数据的接收和发送"></a>（7）数据的接收和发送</h4><p>数据收发函数有几组：</p>
<ul>
<li>read()/write()</li>
<li>recv()/send()</li>
<li>readv()/writev()</li>
<li>recvmsg()/sendmsg()</li>
<li>recvfrom()/sendto()</li>
</ul>
<p>函数原型：</p>
<pre class=" language-c"><code class="language-c">ssize_t <span class="token function">read</span><span class="token punctuation">(</span><span class="token keyword">int</span> fd<span class="token punctuation">,</span> <span class="token keyword">void</span> <span class="token operator">*</span>buf<span class="token punctuation">,</span> size_t count<span class="token punctuation">)</span><span class="token punctuation">;</span>
ssize_t <span class="token function">write</span><span class="token punctuation">(</span><span class="token keyword">int</span> fd<span class="token punctuation">,</span> <span class="token keyword">const</span> <span class="token keyword">void</span> <span class="token operator">*</span>buf<span class="token punctuation">,</span> size_t count<span class="token punctuation">)</span><span class="token punctuation">;</span>
ssize_t <span class="token function">send</span><span class="token punctuation">(</span><span class="token keyword">int</span> sockfd<span class="token punctuation">,</span> <span class="token keyword">const</span> <span class="token keyword">void</span> <span class="token operator">*</span>buf<span class="token punctuation">,</span> size_t len<span class="token punctuation">,</span> <span class="token keyword">int</span> flags<span class="token punctuation">)</span><span class="token punctuation">;</span>
ssize_t <span class="token function">recv</span><span class="token punctuation">(</span><span class="token keyword">int</span> sockfd<span class="token punctuation">,</span> <span class="token keyword">void</span> <span class="token operator">*</span>buf<span class="token punctuation">,</span> size_t len<span class="token punctuation">,</span> <span class="token keyword">int</span> flags<span class="token punctuation">)</span><span class="token punctuation">;</span>
ssize_t <span class="token function">sendto</span><span class="token punctuation">(</span><span class="token keyword">int</span> sockfd<span class="token punctuation">,</span> <span class="token keyword">const</span> <span class="token keyword">void</span> <span class="token operator">*</span>buf<span class="token punctuation">,</span> size_t len<span class="token punctuation">,</span> <span class="token keyword">int</span> flags<span class="token punctuation">,</span>
                      <span class="token keyword">const</span> <span class="token keyword">struct</span> sockaddr <span class="token operator">*</span>dest_addr<span class="token punctuation">,</span> socklen_t addrlen<span class="token punctuation">)</span><span class="token punctuation">;</span>
ssize_t <span class="token function">recvfrom</span><span class="token punctuation">(</span><span class="token keyword">int</span> sockfd<span class="token punctuation">,</span> <span class="token keyword">void</span> <span class="token operator">*</span>buf<span class="token punctuation">,</span> size_t len<span class="token punctuation">,</span> <span class="token keyword">int</span> flags<span class="token punctuation">,</span>
                        <span class="token keyword">struct</span> sockaddr <span class="token operator">*</span>src_addr<span class="token punctuation">,</span> socklen_t <span class="token operator">*</span>addrlen<span class="token punctuation">)</span><span class="token punctuation">;</span>
ssize_t <span class="token function">sendmsg</span><span class="token punctuation">(</span><span class="token keyword">int</span> sockfd<span class="token punctuation">,</span> <span class="token keyword">const</span> <span class="token keyword">struct</span> msghdr <span class="token operator">*</span>msg<span class="token punctuation">,</span> <span class="token keyword">int</span> flags<span class="token punctuation">)</span><span class="token punctuation">;</span>
ssize_t <span class="token function">recvmsg</span><span class="token punctuation">(</span><span class="token keyword">int</span> sockfd<span class="token punctuation">,</span> <span class="token keyword">struct</span> msghdr <span class="token operator">*</span>msg<span class="token punctuation">,</span> <span class="token keyword">int</span> flags<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>这里介绍一下recv()/send()、recvfrom()/sendto()。</p>
<p><strong>recv()函数：</strong></p>
<pre class=" language-c"><code class="language-c">ssize_t <span class="token function">recv</span><span class="token punctuation">(</span><span class="token keyword">int</span> sockfd<span class="token punctuation">,</span> <span class="token keyword">void</span> <span class="token operator">*</span>buf<span class="token punctuation">,</span> size_t len<span class="token punctuation">,</span> <span class="token keyword">int</span> flags<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<ul>
<li>sockfd参数：sockfd为要接收数据的套接字。</li>
<li>buf参数：buf 为要接收的数据的缓冲区地址。</li>
<li>len参数：len 为要接收的数据的字节数。</li>
<li>flags参数：flags 为接收数据时的选项，常设为0。</li>
</ul>
<p><strong>send()函数：</strong></p>
<pre class=" language-c"><code class="language-c">ssize_t <span class="token function">send</span><span class="token punctuation">(</span><span class="token keyword">int</span> sockfd<span class="token punctuation">,</span> <span class="token keyword">const</span> <span class="token keyword">void</span> <span class="token operator">*</span>buf<span class="token punctuation">,</span> size_t len<span class="token punctuation">,</span> <span class="token keyword">int</span> flags<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<ul>
<li>sockfd参数：sockfd为要发送数据的套接字。</li>
<li>buf参数：buf 为要发送的数据的缓冲区地址。</li>
<li>len参数：len 为要发送的数据的字节数。</li>
<li>flags参数：flags 为发送数据时的选项，常设为0。</li>
</ul>
<p><strong>recvfrom()函数：</strong></p>
<pre class=" language-c"><code class="language-c">ssize_t <span class="token function">recvfrom</span><span class="token punctuation">(</span><span class="token keyword">int</span> sock<span class="token punctuation">,</span> <span class="token keyword">void</span> <span class="token operator">*</span>buf<span class="token punctuation">,</span> size_t nbytes<span class="token punctuation">,</span> <span class="token keyword">int</span> flags<span class="token punctuation">,</span> <span class="token keyword">struct</span> sockadr <span class="token operator">*</span>from<span class="token punctuation">,</span> socklen_t <span class="token operator">*</span>addrlen<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<ul>
<li>sock：用于接收UDP数据的套接字；</li>
<li>buf：保存接收数据的缓冲区地址；</li>
<li>nbytes：可接收的最大字节数（不能超过buf缓冲区的大小）；</li>
<li>flags：可选项参数，若没有可传递0；</li>
<li>from：存有发送端地址信息的sockaddr结构体变量的地址；</li>
<li>addrlen：保存参数 from 的结构体变量长度的变量地址值。</li>
</ul>
<p><strong>sendto()函数：</strong></p>
<pre class=" language-c"><code class="language-c">ssize_t <span class="token function">sendto</span><span class="token punctuation">(</span><span class="token keyword">int</span> sock<span class="token punctuation">,</span> <span class="token keyword">void</span> <span class="token operator">*</span>buf<span class="token punctuation">,</span> size_t nbytes<span class="token punctuation">,</span> <span class="token keyword">int</span> flags<span class="token punctuation">,</span> <span class="token keyword">struct</span> sockaddr <span class="token operator">*</span>to<span class="token punctuation">,</span> socklen_t addrlen<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<ul>
<li>sock：用于传输UDP数据的套接字；</li>
<li>buf：保存待传输数据的缓冲区地址；</li>
<li>nbytes：带传输数据的长度（以字节计）；</li>
<li>flags：可选项参数，若没有可传递0；</li>
<li>to：存有目标地址信息的 sockaddr 结构体变量的地址；</li>
<li>addrlen：传递给参数 to 的地址值结构体变量的长度。</li>
</ul>
<h3 id="2、windows下的socket-API接口"><a href="#2、windows下的socket-API接口" class="headerlink" title="2、windows下的socket API接口"></a>2、windows下的socket API接口</h3><p>跟Linux下的差不多：</p>
<pre class=" language-c"><code class="language-c">SOCKET <span class="token function">socket</span><span class="token punctuation">(</span><span class="token keyword">int</span> af<span class="token punctuation">,</span> <span class="token keyword">int</span> type<span class="token punctuation">,</span> <span class="token keyword">int</span> protocol<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">int</span> <span class="token function">bind</span><span class="token punctuation">(</span>SOCKET sock<span class="token punctuation">,</span> <span class="token keyword">const</span> <span class="token keyword">struct</span> sockaddr <span class="token operator">*</span>addr<span class="token punctuation">,</span> <span class="token keyword">int</span> addrlen<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">int</span> <span class="token function">connect</span><span class="token punctuation">(</span>SOCKET sock<span class="token punctuation">,</span> <span class="token keyword">const</span> <span class="token keyword">struct</span> sockaddr <span class="token operator">*</span>serv_addr<span class="token punctuation">,</span> <span class="token keyword">int</span> addrlen<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">int</span> <span class="token function">listen</span><span class="token punctuation">(</span>SOCKET sock<span class="token punctuation">,</span> <span class="token keyword">int</span> backlog<span class="token punctuation">)</span><span class="token punctuation">;</span>
SOCKET <span class="token function">accept</span><span class="token punctuation">(</span>SOCKET sock<span class="token punctuation">,</span> <span class="token keyword">struct</span> sockaddr <span class="token operator">*</span>addr<span class="token punctuation">,</span> <span class="token keyword">int</span> <span class="token operator">*</span>addrlen<span class="token punctuation">)</span><span class="token punctuation">;</span> 
<span class="token keyword">int</span> <span class="token function">closesocket</span><span class="token punctuation">(</span> SOCKET s<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">int</span> <span class="token function">send</span><span class="token punctuation">(</span>SOCKET sock<span class="token punctuation">,</span> <span class="token keyword">const</span> <span class="token keyword">char</span> <span class="token operator">*</span>buf<span class="token punctuation">,</span> <span class="token keyword">int</span> len<span class="token punctuation">,</span> <span class="token keyword">int</span> flags<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">int</span> <span class="token function">recv</span><span class="token punctuation">(</span>SOCKET sock<span class="token punctuation">,</span> <span class="token keyword">char</span> <span class="token operator">*</span>buf<span class="token punctuation">,</span> <span class="token keyword">int</span> len<span class="token punctuation">,</span> <span class="token keyword">int</span> flags<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">int</span> <span class="token function">recvfrom</span><span class="token punctuation">(</span>SOCKET sock<span class="token punctuation">,</span> <span class="token keyword">char</span> <span class="token operator">*</span>buf<span class="token punctuation">,</span> <span class="token keyword">int</span> nbytes<span class="token punctuation">,</span> <span class="token keyword">int</span> flags<span class="token punctuation">,</span> <span class="token keyword">const</span> <span class="token keyword">struct</span> sockaddr <span class="token operator">*</span>from<span class="token punctuation">,</span> <span class="token keyword">int</span> <span class="token operator">*</span>addrlen<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">int</span> <span class="token function">sendto</span><span class="token punctuation">(</span>SOCKET sock<span class="token punctuation">,</span> <span class="token keyword">const</span> <span class="token keyword">char</span> <span class="token operator">*</span>buf<span class="token punctuation">,</span> <span class="token keyword">int</span> nbytes<span class="token punctuation">,</span> <span class="token keyword">int</span> flags<span class="token punctuation">,</span> <span class="token keyword">const</span> <span class="token keyword">struct</span> sockadr <span class="token operator">*</span>to<span class="token punctuation">,</span> <span class="token keyword">int</span> addrlen<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<h3 id="3、TCP、UDP通信的socket编程过程图"><a href="#3、TCP、UDP通信的socket编程过程图" class="headerlink" title="3、TCP、UDP通信的socket编程过程图"></a>3、TCP、UDP通信的socket编程过程图</h3><p><strong>（1）TCP通信socket编程过程</strong></p>
<p><img src="https://s2.ax1x.com/2019/07/01/Z37yzq.png" alt></p>
<p><strong>（2）UDP通信socket编程过程</strong></p>
<p><img src="https://s2.ax1x.com/2019/07/01/Z372LT.png" alt></p>
<h2 id="四、socket的应用实例"><a href="#四、socket的应用实例" class="headerlink" title="四、socket的应用实例"></a>四、socket的应用实例</h2><h3 id="1、基于TCP的本地客户端、服务端信息交互实例"><a href="#1、基于TCP的本地客户端、服务端信息交互实例" class="headerlink" title="1、基于TCP的本地客户端、服务端信息交互实例"></a>1、基于TCP的本地客户端、服务端信息交互实例</h3><p>本例的例子实现的功能为：本地TCP客户端往本地TCP服务端发送数据，TCP服务端收到数据则会打印输出，同时把原数据返回给TCP客户端。这个例子类似于我们在做单片机的串口实验时，串口上位机往我们的单片机发送数据，单片机收到数据则把该数据原样返回给上位机。</p>
<p><strong>（1）windows的程序：</strong></p>
<p><strong>服务端程序tcp_server.c：</strong></p>
<pre class=" language-c"><code class="language-c"><span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;stdio.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;winsock2.h></span></span>

<span class="token macro property">#<span class="token directive keyword">define</span> BUF_LEN  100</span>

<span class="token keyword">int</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token keyword">void</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    WSADATA wd<span class="token punctuation">;</span>
    SOCKET ServerSock<span class="token punctuation">,</span> ClientSock<span class="token punctuation">;</span>
    <span class="token keyword">char</span> Buf<span class="token punctuation">[</span>BUF_LEN<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token number">0</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
    SOCKADDR ClientAddr<span class="token punctuation">;</span>
    SOCKADDR_IN ServerSockAddr<span class="token punctuation">;</span>
    <span class="token keyword">int</span> addr_size <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">,</span> recv_len <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/* 初始化操作sock需要的DLL */</span>
    <span class="token function">WSAStartup</span><span class="token punctuation">(</span><span class="token function">MAKEWORD</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token operator">&amp;</span>wd<span class="token punctuation">)</span><span class="token punctuation">;</span>  

    <span class="token comment" spellcheck="true">/* 创建服务端socket */</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span> <span class="token operator">==</span> <span class="token punctuation">(</span>ServerSock <span class="token operator">=</span> <span class="token function">socket</span><span class="token punctuation">(</span>AF_INET<span class="token punctuation">,</span> SOCK_STREAM<span class="token punctuation">,</span> IPPROTO_TCP<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"socket error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/* 设置服务端信息 */</span>
    <span class="token function">memset</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>ServerSockAddr<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>ServerSockAddr<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>     <span class="token comment" spellcheck="true">// 给结构体ServerSockAddr清零</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_family <span class="token operator">=</span> AF_INET<span class="token punctuation">;</span>                      <span class="token comment" spellcheck="true">// 使用IPv4地址</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_addr<span class="token punctuation">.</span>s_addr <span class="token operator">=</span> <span class="token function">inet_addr</span><span class="token punctuation">(</span><span class="token string">"127.0.0.1"</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment" spellcheck="true">// 本机IP地址</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_port <span class="token operator">=</span> <span class="token function">htons</span><span class="token punctuation">(</span><span class="token number">1314</span><span class="token punctuation">)</span><span class="token punctuation">;</span>                  <span class="token comment" spellcheck="true">// 端口</span>

    <span class="token comment" spellcheck="true">/* 绑定套接字 */</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span> <span class="token operator">==</span> <span class="token function">bind</span><span class="token punctuation">(</span>ServerSock<span class="token punctuation">,</span> <span class="token punctuation">(</span>SOCKADDR<span class="token operator">*</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>ServerSockAddr<span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>SOCKADDR<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"bind error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/* 进入监听状态 */</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span> <span class="token operator">==</span> <span class="token function">listen</span><span class="token punctuation">(</span>ServerSock<span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"listen error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    addr_size <span class="token operator">=</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>SOCKADDR<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">/* 监听客户端请求，accept函数返回一个新的套接字，发送和接收都是用这个套接字 */</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span> <span class="token operator">==</span> <span class="token punctuation">(</span>ClientSock <span class="token operator">=</span> <span class="token function">accept</span><span class="token punctuation">(</span>ServerSock<span class="token punctuation">,</span> <span class="token punctuation">(</span>SOCKADDR<span class="token operator">*</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>ClientAddr<span class="token punctuation">,</span> <span class="token operator">&amp;</span>addr_size<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
        <span class="token punctuation">{</span>
            <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"socket error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

        <span class="token comment" spellcheck="true">/* 接受客户端的返回数据 */</span>
        <span class="token keyword">int</span> recv_len <span class="token operator">=</span> <span class="token function">recv</span><span class="token punctuation">(</span>ClientSock<span class="token punctuation">,</span> Buf<span class="token punctuation">,</span> BUF_LEN<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"客户端发送过来的数据为：%s\n"</span><span class="token punctuation">,</span> Buf<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">/* 发送数据到客户端 */</span>
        <span class="token function">send</span><span class="token punctuation">(</span>ClientSock<span class="token punctuation">,</span> Buf<span class="token punctuation">,</span> recv_len<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">/* 关闭客户端套接字 */</span>
        <span class="token function">closesocket</span><span class="token punctuation">(</span>ClientSock<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">/* 清空缓冲区 */</span>
        <span class="token function">memset</span><span class="token punctuation">(</span>Buf<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> BUF_LEN<span class="token punctuation">)</span><span class="token punctuation">;</span>  
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/*如果有退出循环的条件，这里还需要清除对socket库的使用*/</span>
    <span class="token comment" spellcheck="true">/* 关闭服务端套接字 */</span>
    <span class="token comment" spellcheck="true">//closesocket(ServerSock);</span>
    <span class="token comment" spellcheck="true">/* WSACleanup();*/</span>

    <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p><strong>客户端程序tcp_client.c：</strong></p>
<pre class=" language-c"><code class="language-c"><span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;stdio.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;winsock2.h></span></span>

<span class="token macro property">#<span class="token directive keyword">define</span> BUF_LEN  100</span>

<span class="token keyword">int</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token keyword">void</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    WSADATA wd<span class="token punctuation">;</span>
    SOCKET ClientSock<span class="token punctuation">;</span>
    <span class="token keyword">char</span> Buf<span class="token punctuation">[</span>BUF_LEN<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token number">0</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
    SOCKADDR_IN  ServerSockAddr<span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/* 初始化操作sock需要的DLL */</span>
    <span class="token function">WSAStartup</span><span class="token punctuation">(</span><span class="token function">MAKEWORD</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token operator">&amp;</span>wd<span class="token punctuation">)</span><span class="token punctuation">;</span>  

    <span class="token comment" spellcheck="true">/* 向服务器发起请求 */</span>
    <span class="token function">memset</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>ServerSockAddr<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>ServerSockAddr<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
    ServerSockAddr<span class="token punctuation">.</span>sin_family <span class="token operator">=</span> AF_INET<span class="token punctuation">;</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_addr<span class="token punctuation">.</span>s_addr <span class="token operator">=</span> <span class="token function">inet_addr</span><span class="token punctuation">(</span><span class="token string">"127.0.0.1"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_port <span class="token operator">=</span> <span class="token function">htons</span><span class="token punctuation">(</span><span class="token number">1314</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">/* 创建客户端socket */</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span> <span class="token operator">==</span> <span class="token punctuation">(</span>ClientSock <span class="token operator">=</span> <span class="token function">socket</span><span class="token punctuation">(</span>AF_INET<span class="token punctuation">,</span> SOCK_STREAM<span class="token punctuation">,</span> IPPROTO_TCP<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
        <span class="token punctuation">{</span>
            <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"socket error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span> <span class="token operator">==</span> <span class="token function">connect</span><span class="token punctuation">(</span>ClientSock<span class="token punctuation">,</span> <span class="token punctuation">(</span>SOCKADDR<span class="token operator">*</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>ServerSockAddr<span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>SOCKADDR<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
        <span class="token punctuation">{</span>
            <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"connect error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"请输入一个字符串，发送给服务端："</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">gets</span><span class="token punctuation">(</span>Buf<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment" spellcheck="true">/* 发送数据到服务端 */</span>
        <span class="token function">send</span><span class="token punctuation">(</span>ClientSock<span class="token punctuation">,</span> Buf<span class="token punctuation">,</span> <span class="token function">strlen</span><span class="token punctuation">(</span>Buf<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">/* 接受服务端的返回数据 */</span>
        <span class="token function">recv</span><span class="token punctuation">(</span>ClientSock<span class="token punctuation">,</span> Buf<span class="token punctuation">,</span> BUF_LEN<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"服务端发送过来的数据为：%s\n"</span><span class="token punctuation">,</span> Buf<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token function">memset</span><span class="token punctuation">(</span>Buf<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> BUF_LEN<span class="token punctuation">)</span><span class="token punctuation">;</span>   <span class="token comment" spellcheck="true">// 重置缓冲区</span>
        <span class="token function">closesocket</span><span class="token punctuation">(</span>ClientSock<span class="token punctuation">)</span><span class="token punctuation">;</span>   <span class="token comment" spellcheck="true">// 关闭套接字</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">// WSACleanup();  </span><span class="token comment" spellcheck="true">/*如果有退出循环的条件，这里还需要清除对socket库的使用*/</span>
    <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p>我们上边的IP地址概念那一部分中，有强调<code>127.0.0.1</code>这个IP是一个特殊的IP地址，这是回送地址，即本地机，一般用来测试使用。这个例子中我们就用到了。此外，端口我们设置为<code>1314</code>，这是随意设置的，只要范围在<code>1024~65536</code>之间就可以。</p>
<p>本文使用的是gcc编译器编译（关于gcc编译器的相关介绍可查看往期笔记：<a href="https://zhengnianli.github.io/2018/10/05/c-yu-yan-bi-ji-shi-yong-notepad-mingw-lai-kai-fa-c-cheng-xu/" target="_blank" rel="noopener">【C语言笔记】使用notepad++、MinGW来开发C程序</a>及<a href="https://zhengnianli.github.io/2018/12/23/c-yu-yan-bi-ji-windows-ming-ling-xing-xia-bian-yi-c-cheng-xu/" target="_blank" rel="noopener">【C语言笔记】windows命令行下编译C程序</a>），编译命令如下：</p>
<pre class=" language-c"><code class="language-c">gcc tcp_client<span class="token punctuation">.</span>c <span class="token operator">-</span>o tcp_client<span class="token punctuation">.</span>exe <span class="token operator">-</span>lwsock32
gcc tcp_server<span class="token punctuation">.</span>c <span class="token operator">-</span>o tcp_server<span class="token punctuation">.</span>exe <span class="token operator">-</span>lwsock32</code></pre>
<p>这里必须要加<code>-lwsock32</code>这个参数用于链接windows下socket编程必须的winsock2这个库。若是使用集成开发环境，则需要把<code>wsock32.lib</code>放在工程目录下，并在我们代码中<code>#include &lt;winsock2.h&gt;</code> 下面加上一行 <code>#pragma comment(lib, &quot;ws2_32.lib&quot;)</code>代码（这种情况本人未验证，有兴趣的朋友可尝试）。</p>
<p><strong>实验现象：</strong></p>
<p>先启动服务端程序<code>tcp_server.exe</code>，再启动客户端程序<code>tcp_client.exe</code>，并在客户端中输入字符串，则当服务端会接收到字符串时会打印输出，与此同时也会往客户端返回相同的数据：</p>
<p><img src="https://s2.ax1x.com/2019/06/30/Z1zBss.png" alt></p>
<p><strong>动图：</strong></p>
<p><img src="http://i65.tinypic.com/20t31iv.gif" alt="实验结果"></p>
<p><strong>（2）Linux的程序：</strong></p>
<p>在linux下，“一切都是文件”，所以这里我们的套接字也当做文件来看待。</p>
<p><strong>服务端程序linux_tcp_server.c：</strong></p>
<pre class=" language-c"><code class="language-c"><span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;stdio.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;string.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;stdlib.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;unistd.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;arpa/inet.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;sys/socket.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;netinet/in.h></span></span>

<span class="token macro property">#<span class="token directive keyword">define</span> BUF_LEN  100</span>

<span class="token keyword">int</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token keyword">void</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    <span class="token keyword">int</span> ServerFd<span class="token punctuation">,</span> ClientFd<span class="token punctuation">;</span>                
    <span class="token keyword">char</span> Buf<span class="token punctuation">[</span>BUF_LEN<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token number">0</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
    <span class="token keyword">struct</span> sockaddr ClientAddr<span class="token punctuation">;</span>
    <span class="token keyword">int</span> addr_len <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">,</span> recv_len <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token keyword">struct</span> sockaddr_in ServerSockAddr<span class="token punctuation">;</span>  
    <span class="token keyword">int</span> optval <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span> 

    <span class="token comment" spellcheck="true">/* 创建服务端文件描述符 */</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span> <span class="token operator">==</span> <span class="token punctuation">(</span>ServerFd <span class="token operator">=</span> <span class="token function">socket</span><span class="token punctuation">(</span>AF_INET<span class="token punctuation">,</span> SOCK_STREAM<span class="token punctuation">,</span> IPPROTO_TCP<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"socket error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/* 设置服务端信息 */</span>

    <span class="token function">memset</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>ServerSockAddr<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>ServerSockAddr<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>     <span class="token comment" spellcheck="true">// 给结构体ServerSockAddr清零</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_family <span class="token operator">=</span> AF_INET<span class="token punctuation">;</span>                      <span class="token comment" spellcheck="true">// 使用IPv4地址</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_addr<span class="token punctuation">.</span>s_addr <span class="token operator">=</span> <span class="token function">htonl</span><span class="token punctuation">(</span>INADDR_ANY<span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token comment" spellcheck="true">// 自动获取IP地址</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_port <span class="token operator">=</span> <span class="token function">htons</span><span class="token punctuation">(</span><span class="token number">6666</span><span class="token punctuation">)</span><span class="token punctuation">;</span>                  <span class="token comment" spellcheck="true">// 端口</span>


    <span class="token comment" spellcheck="true">// 设置地址和端口号可以重复使用  </span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">setsockopt</span><span class="token punctuation">(</span>ServerFd<span class="token punctuation">,</span> SOL_SOCKET<span class="token punctuation">,</span> SO_REUSEADDR<span class="token punctuation">,</span> <span class="token operator">&amp;</span>optval<span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>optval<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">&lt;</span> <span class="token number">0</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"setsockopt error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/* 绑定操作，绑定前加上上面的socket属性可重复使用地址 */</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span> <span class="token operator">==</span> <span class="token function">bind</span><span class="token punctuation">(</span>ServerFd<span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token keyword">struct</span> sockaddr<span class="token operator">*</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>ServerSockAddr<span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span><span class="token keyword">struct</span> sockaddr<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"bind error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/* 进入监听状态 */</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span> <span class="token operator">==</span> <span class="token punctuation">(</span><span class="token function">listen</span><span class="token punctuation">(</span>ServerFd<span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"listen error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    addr_len <span class="token operator">=</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span><span class="token keyword">struct</span> sockaddr<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">/* 监听客户端请求，accept函数返回一个新的套接字，发送和接收都是用这个套接字 */</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span> <span class="token operator">==</span> <span class="token punctuation">(</span>ClientFd <span class="token operator">=</span> <span class="token function">accept</span><span class="token punctuation">(</span>ServerFd<span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token keyword">struct</span> sockaddr<span class="token operator">*</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>ClientAddr<span class="token punctuation">,</span> <span class="token operator">&amp;</span>addr_len<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
        <span class="token punctuation">{</span>
            <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"accept error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

        <span class="token comment" spellcheck="true">/* 接受客户端的返回数据 */</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token punctuation">(</span>recv_len <span class="token operator">=</span> <span class="token function">recv</span><span class="token punctuation">(</span>ClientFd<span class="token punctuation">,</span> Buf<span class="token punctuation">,</span> BUF_LEN<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">&lt;</span> <span class="token number">0</span><span class="token punctuation">)</span>
        <span class="token punctuation">{</span>
            <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"recv error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"客户端发送过来的数据为：%s\n"</span><span class="token punctuation">,</span> Buf<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">/* 发送数据到客户端 */</span>
        <span class="token function">send</span><span class="token punctuation">(</span>ClientFd<span class="token punctuation">,</span> Buf<span class="token punctuation">,</span> recv_len<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">/* 关闭客户端套接字 */</span>
        <span class="token function">close</span><span class="token punctuation">(</span>ClientFd<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">/* 清空缓冲区 */</span>
        <span class="token function">memset</span><span class="token punctuation">(</span>Buf<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> BUF_LEN<span class="token punctuation">)</span><span class="token punctuation">;</span>  
    <span class="token punctuation">}</span>

    <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p><strong>客户端程序linux_tcp_client.c：</strong></p>
<pre class=" language-c"><code class="language-c"><span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;stdio.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;string.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;stdlib.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;unistd.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;arpa/inet.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;sys/socket.h></span></span>

<span class="token macro property">#<span class="token directive keyword">define</span> BUF_LEN  100</span>

<span class="token keyword">int</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token keyword">void</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    <span class="token keyword">int</span> ClientFd<span class="token punctuation">;</span>
    <span class="token keyword">char</span> Buf<span class="token punctuation">[</span>BUF_LEN<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token number">0</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
    <span class="token keyword">struct</span> sockaddr_in  ServerSockAddr<span class="token punctuation">;</span>


    <span class="token comment" spellcheck="true">/* 向服务器发起请求 */</span>
    <span class="token function">memset</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>ServerSockAddr<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>ServerSockAddr<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
    ServerSockAddr<span class="token punctuation">.</span>sin_family <span class="token operator">=</span> AF_INET<span class="token punctuation">;</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_addr<span class="token punctuation">.</span>s_addr <span class="token operator">=</span> <span class="token function">inet_addr</span><span class="token punctuation">(</span><span class="token string">"127.0.0.1"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_port <span class="token operator">=</span> <span class="token function">htons</span><span class="token punctuation">(</span><span class="token number">6666</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">/* 创建客户端socket */</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span> <span class="token operator">==</span> <span class="token punctuation">(</span>ClientFd <span class="token operator">=</span> <span class="token function">socket</span><span class="token punctuation">(</span>AF_INET<span class="token punctuation">,</span> SOCK_STREAM<span class="token punctuation">,</span> IPPROTO_TCP<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
        <span class="token punctuation">{</span>
            <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"socket error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

        <span class="token comment" spellcheck="true">/* 连接 */</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span> <span class="token operator">==</span> <span class="token function">connect</span><span class="token punctuation">(</span>ClientFd<span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token keyword">struct</span> sockaddr<span class="token operator">*</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>ServerSockAddr<span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>ServerSockAddr<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
        <span class="token punctuation">{</span>
            <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"connect error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"请输入一个字符串，发送给服务端："</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">gets</span><span class="token punctuation">(</span>Buf<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment" spellcheck="true">/* 发送数据到服务端 */</span>
        <span class="token function">send</span><span class="token punctuation">(</span>ClientFd<span class="token punctuation">,</span> Buf<span class="token punctuation">,</span> <span class="token function">strlen</span><span class="token punctuation">(</span>Buf<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">memset</span><span class="token punctuation">(</span>Buf<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> BUF_LEN<span class="token punctuation">)</span><span class="token punctuation">;</span>   <span class="token comment" spellcheck="true">// 重置缓冲区</span>

        <span class="token comment" spellcheck="true">/* 接受服务端的返回数据 */</span>
        <span class="token function">recv</span><span class="token punctuation">(</span>ClientFd<span class="token punctuation">,</span> Buf<span class="token punctuation">,</span> BUF_LEN<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"服务端发送过来的数据为：%s\n"</span><span class="token punctuation">,</span> Buf<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token function">memset</span><span class="token punctuation">(</span>Buf<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> BUF_LEN<span class="token punctuation">)</span><span class="token punctuation">;</span>   <span class="token comment" spellcheck="true">// 重置缓冲区</span>
        <span class="token function">close</span><span class="token punctuation">(</span>ClientFd<span class="token punctuation">)</span><span class="token punctuation">;</span>   <span class="token comment" spellcheck="true">// 关闭套接字</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p>Linux下编译就不需要添加<code>-lwsock32</code>参数：</p>
<pre class=" language-c"><code class="language-c">gcc linux_tcp_server<span class="token punctuation">.</span>c <span class="token operator">-</span>o linux_tcp_server
gcc linux_tcp_client<span class="token punctuation">.</span>c <span class="token operator">-</span>o linux_tcp_client</code></pre>
<p><strong>实验现象：</strong></p>
<p><img src="https://s2.ax1x.com/2019/07/01/Z34TAA.png" alt></p>
<p>在调试这份程序时，出现了绑定错误：</p>
<p><img src="https://s2.ax1x.com/2019/07/01/Z34z7j.png" alt></p>
<p>经上网查询发现是端口重复使用，可以在调用<code>bind()</code>函数之前调用<code>setsockopt()</code>函数以解决端口重复使用的问题：</p>
<p><img src="https://s2.ax1x.com/2019/07/01/Z35NEd.png" alt></p>
<h3 id="2、基于UDP的本地客户端、服务端信息交互实例"><a href="#2、基于UDP的本地客户端、服务端信息交互实例" class="headerlink" title="2、基于UDP的本地客户端、服务端信息交互实例"></a>2、基于UDP的本地客户端、服务端信息交互实例</h3><p><strong>（1）windows的程序</strong></p>
<p><strong>服务端程序udp_server.c：</strong></p>
<pre class=" language-c"><code class="language-c"><span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;stdio.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;winsock2.h></span></span>

<span class="token macro property">#<span class="token directive keyword">define</span> BUF_LEN  100</span>

<span class="token keyword">int</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token keyword">void</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    WSADATA wd<span class="token punctuation">;</span>
    SOCKET ServerSock<span class="token punctuation">;</span>
    <span class="token keyword">char</span> Buf<span class="token punctuation">[</span>BUF_LEN<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token number">0</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
    SOCKADDR ClientAddr<span class="token punctuation">;</span>
    SOCKADDR_IN ServerSockAddr<span class="token punctuation">;</span>
    <span class="token keyword">int</span> addr_size <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>


    <span class="token comment" spellcheck="true">/* 初始化操作sock需要的DLL */</span>
    <span class="token function">WSAStartup</span><span class="token punctuation">(</span><span class="token function">MAKEWORD</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token operator">&amp;</span>wd<span class="token punctuation">)</span><span class="token punctuation">;</span>  

    <span class="token comment" spellcheck="true">/* 创建服务端socket */</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span> <span class="token operator">==</span> <span class="token punctuation">(</span>ServerSock <span class="token operator">=</span> <span class="token function">socket</span><span class="token punctuation">(</span>AF_INET<span class="token punctuation">,</span> SOCK_DGRAM<span class="token punctuation">,</span> IPPROTO_UDP<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"socket error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/* 设置服务端信息 */</span>
    <span class="token function">memset</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>ServerSockAddr<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>ServerSockAddr<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>     <span class="token comment" spellcheck="true">// 给结构体ServerSockAddr清零</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_family <span class="token operator">=</span> AF_INET<span class="token punctuation">;</span>                      <span class="token comment" spellcheck="true">// 使用IPv4地址</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_addr<span class="token punctuation">.</span>s_addr <span class="token operator">=</span> <span class="token function">htonl</span><span class="token punctuation">(</span>INADDR_ANY<span class="token punctuation">)</span><span class="token punctuation">;</span>     <span class="token comment" spellcheck="true">// 自动获取IP地址</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_port <span class="token operator">=</span> <span class="token function">htons</span><span class="token punctuation">(</span><span class="token number">1314</span><span class="token punctuation">)</span><span class="token punctuation">;</span>                  <span class="token comment" spellcheck="true">// 端口</span>

    <span class="token comment" spellcheck="true">/* 绑定套接字 */</span>

    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span> <span class="token operator">==</span> <span class="token punctuation">(</span><span class="token function">bind</span><span class="token punctuation">(</span>ServerSock<span class="token punctuation">,</span> <span class="token punctuation">(</span>SOCKADDR<span class="token operator">*</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>ServerSockAddr<span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>SOCKADDR<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"bind error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    addr_size <span class="token operator">=</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>SOCKADDR<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">/* 接受客户端的返回数据 */</span>
        <span class="token keyword">int</span> str_len <span class="token operator">=</span> <span class="token function">recvfrom</span><span class="token punctuation">(</span>ServerSock<span class="token punctuation">,</span> Buf<span class="token punctuation">,</span> BUF_LEN<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token operator">&amp;</span>ClientAddr<span class="token punctuation">,</span> <span class="token operator">&amp;</span>addr_size<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"客户端发送过来的数据为：%s\n"</span><span class="token punctuation">,</span> Buf<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">/* 发送数据到客户端 */</span>
        <span class="token function">sendto</span><span class="token punctuation">(</span>ServerSock<span class="token punctuation">,</span> Buf<span class="token punctuation">,</span> str_len<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token operator">&amp;</span>ClientAddr<span class="token punctuation">,</span> addr_size<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">/* 清空缓冲区 */</span>
        <span class="token function">memset</span><span class="token punctuation">(</span>Buf<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> BUF_LEN<span class="token punctuation">)</span><span class="token punctuation">;</span>  
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/*如果有退出循环的条件，这里还需要清除对socket库的使用*/</span>
    <span class="token comment" spellcheck="true">/* 关闭服务端套接字 */</span>
    <span class="token comment" spellcheck="true">//closesocket(ServerSock);</span>
    <span class="token comment" spellcheck="true">/* WSACleanup();*/</span>

    <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p><strong>客户端程序udp_client.c：</strong></p>
<pre class=" language-c"><code class="language-c"><span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;stdio.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;winsock2.h></span></span>

<span class="token macro property">#<span class="token directive keyword">define</span> BUF_LEN  100</span>

<span class="token keyword">int</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token keyword">void</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    WSADATA wd<span class="token punctuation">;</span>
    SOCKET ClientSock<span class="token punctuation">;</span>
    <span class="token keyword">char</span> Buf<span class="token punctuation">[</span>BUF_LEN<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token number">0</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
    SOCKADDR ServerAddr<span class="token punctuation">;</span>
    SOCKADDR_IN  ServerSockAddr<span class="token punctuation">;</span>
    <span class="token keyword">int</span> ServerAddrLen <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/* 初始化操作sock需要的DLL */</span>
    <span class="token function">WSAStartup</span><span class="token punctuation">(</span><span class="token function">MAKEWORD</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token operator">&amp;</span>wd<span class="token punctuation">)</span><span class="token punctuation">;</span>  

    <span class="token comment" spellcheck="true">/* 创建客户端socket */</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span> <span class="token operator">==</span> <span class="token punctuation">(</span>ClientSock <span class="token operator">=</span> <span class="token function">socket</span><span class="token punctuation">(</span>AF_INET<span class="token punctuation">,</span> SOCK_DGRAM<span class="token punctuation">,</span> IPPROTO_UDP<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"socket error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/* 向服务器发起请求 */</span>
    <span class="token function">memset</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>ServerSockAddr<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>ServerSockAddr<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
    ServerSockAddr<span class="token punctuation">.</span>sin_family <span class="token operator">=</span> PF_INET<span class="token punctuation">;</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_addr<span class="token punctuation">.</span>s_addr <span class="token operator">=</span> <span class="token function">inet_addr</span><span class="token punctuation">(</span><span class="token string">"127.0.0.1"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_port <span class="token operator">=</span> <span class="token function">htons</span><span class="token punctuation">(</span><span class="token number">1314</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    ServerAddrLen <span class="token operator">=</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>ServerAddr<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"请输入一个字符串，发送给服务端："</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">gets</span><span class="token punctuation">(</span>Buf<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment" spellcheck="true">/* 发送数据到服务端 */</span>
        <span class="token function">sendto</span><span class="token punctuation">(</span>ClientSock<span class="token punctuation">,</span> Buf<span class="token punctuation">,</span> <span class="token function">strlen</span><span class="token punctuation">(</span>Buf<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token keyword">struct</span> sockaddr<span class="token operator">*</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>ServerSockAddr<span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>ServerSockAddr<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">/* 接受服务端的返回数据 */</span>
        <span class="token function">recvfrom</span><span class="token punctuation">(</span>ClientSock<span class="token punctuation">,</span> Buf<span class="token punctuation">,</span> BUF_LEN<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token operator">&amp;</span>ServerAddr<span class="token punctuation">,</span> <span class="token operator">&amp;</span>ServerAddrLen<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"服务端发送过来的数据为：%s\n"</span><span class="token punctuation">,</span> Buf<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token function">memset</span><span class="token punctuation">(</span>Buf<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> BUF_LEN<span class="token punctuation">)</span><span class="token punctuation">;</span>   <span class="token comment" spellcheck="true">// 重置缓冲区</span>
    <span class="token punctuation">}</span>

    <span class="token function">closesocket</span><span class="token punctuation">(</span>ClientSock<span class="token punctuation">)</span><span class="token punctuation">;</span>   <span class="token comment" spellcheck="true">// 关闭套接字</span>
    <span class="token comment" spellcheck="true">// WSACleanup();  </span><span class="token comment" spellcheck="true">/*如果有退出循环的条件，这里还需要清除对socket库的使用*/</span>
    <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p><strong>（2）Linux下的程序</strong></p>
<p><strong>服务端程序linux_udp_server.c：</strong></p>
<pre class=" language-c"><code class="language-c"><span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;stdio.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;string.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;stdlib.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;unistd.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;arpa/inet.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;sys/socket.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;netinet/in.h></span></span>

<span class="token macro property">#<span class="token directive keyword">define</span> BUF_LEN  100</span>

<span class="token keyword">int</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token keyword">void</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    <span class="token keyword">int</span> ServerFd<span class="token punctuation">;</span>
    <span class="token keyword">char</span> Buf<span class="token punctuation">[</span>BUF_LEN<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token number">0</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
    <span class="token keyword">struct</span> sockaddr ClientAddr<span class="token punctuation">;</span>
    <span class="token keyword">struct</span> sockaddr_in ServerSockAddr<span class="token punctuation">;</span>
    <span class="token keyword">int</span> addr_size <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> 
    <span class="token keyword">int</span> optval <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span> 

    <span class="token comment" spellcheck="true">/* 创建服务端socket */</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span> <span class="token operator">-</span><span class="token number">1</span> <span class="token operator">==</span> <span class="token punctuation">(</span>ServerFd <span class="token operator">=</span> <span class="token function">socket</span><span class="token punctuation">(</span>AF_INET<span class="token punctuation">,</span> SOCK_DGRAM<span class="token punctuation">,</span> IPPROTO_UDP<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"socket error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/* 设置服务端信息 */</span>
    <span class="token function">memset</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>ServerSockAddr<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>ServerSockAddr<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>     <span class="token comment" spellcheck="true">// 给结构体ServerSockAddr清零</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_family <span class="token operator">=</span> AF_INET<span class="token punctuation">;</span>                      <span class="token comment" spellcheck="true">// 使用IPv4地址</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_addr<span class="token punctuation">.</span>s_addr <span class="token operator">=</span> <span class="token function">htonl</span><span class="token punctuation">(</span>INADDR_ANY<span class="token punctuation">)</span><span class="token punctuation">;</span>     <span class="token comment" spellcheck="true">// 自动获取IP地址</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_port <span class="token operator">=</span> <span class="token function">htons</span><span class="token punctuation">(</span><span class="token number">1314</span><span class="token punctuation">)</span><span class="token punctuation">;</span>                  <span class="token comment" spellcheck="true">// 端口</span>

    <span class="token comment" spellcheck="true">// 设置地址和端口号可以重复使用  </span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">setsockopt</span><span class="token punctuation">(</span>ServerFd<span class="token punctuation">,</span> SOL_SOCKET<span class="token punctuation">,</span> SO_REUSEADDR<span class="token punctuation">,</span> <span class="token operator">&amp;</span>optval<span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>optval<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">&lt;</span> <span class="token number">0</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"setsockopt error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/* 绑定操作，绑定前加上上面的socket属性可重复使用地址 */</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span> <span class="token operator">==</span> <span class="token function">bind</span><span class="token punctuation">(</span>ServerFd<span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token keyword">struct</span> sockaddr<span class="token operator">*</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>ServerSockAddr<span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>ServerSockAddr<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"bind error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    addr_size <span class="token operator">=</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>ClientAddr<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">/* 接受客户端的返回数据 */</span>
        <span class="token keyword">int</span> str_len <span class="token operator">=</span> <span class="token function">recvfrom</span><span class="token punctuation">(</span>ServerFd<span class="token punctuation">,</span> Buf<span class="token punctuation">,</span> BUF_LEN<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token operator">&amp;</span>ClientAddr<span class="token punctuation">,</span> <span class="token operator">&amp;</span>addr_size<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"客户端发送过来的数据为：%s\n"</span><span class="token punctuation">,</span> Buf<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">/* 发送数据到客户端 */</span>
        <span class="token function">sendto</span><span class="token punctuation">(</span>ServerFd<span class="token punctuation">,</span> Buf<span class="token punctuation">,</span> str_len<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token operator">&amp;</span>ClientAddr<span class="token punctuation">,</span> addr_size<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">/* 清空缓冲区 */</span>
        <span class="token function">memset</span><span class="token punctuation">(</span>Buf<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> BUF_LEN<span class="token punctuation">)</span><span class="token punctuation">;</span>  
    <span class="token punctuation">}</span>

    <span class="token function">close</span><span class="token punctuation">(</span>ServerFd<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p><strong>客户端程序linux_udp_client.c：</strong></p>
<pre class=" language-c"><code class="language-c"><span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;stdio.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;string.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;stdlib.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;unistd.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;arpa/inet.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;sys/socket.h></span></span>

<span class="token macro property">#<span class="token directive keyword">define</span> BUF_LEN  100</span>

<span class="token keyword">int</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token keyword">void</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    <span class="token keyword">int</span> ClientFd<span class="token punctuation">;</span>
    <span class="token keyword">char</span> Buf<span class="token punctuation">[</span>BUF_LEN<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token number">0</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
    <span class="token keyword">struct</span> sockaddr ServerAddr<span class="token punctuation">;</span>
    <span class="token keyword">int</span> addr_size <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token keyword">struct</span> sockaddr_in  ServerSockAddr<span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/* 创建客户端socket */</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span> <span class="token operator">==</span> <span class="token punctuation">(</span>ClientFd <span class="token operator">=</span> <span class="token function">socket</span><span class="token punctuation">(</span>AF_INET<span class="token punctuation">,</span> SOCK_DGRAM<span class="token punctuation">,</span> IPPROTO_UDP<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"socket error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/* 向服务器发起请求 */</span>
    <span class="token function">memset</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>ServerSockAddr<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>ServerSockAddr<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
    ServerSockAddr<span class="token punctuation">.</span>sin_family <span class="token operator">=</span> PF_INET<span class="token punctuation">;</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_addr<span class="token punctuation">.</span>s_addr <span class="token operator">=</span> <span class="token function">inet_addr</span><span class="token punctuation">(</span><span class="token string">"127.0.0.1"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_port <span class="token operator">=</span> <span class="token function">htons</span><span class="token punctuation">(</span><span class="token number">1314</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    addr_size <span class="token operator">=</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>ServerAddr<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"请输入一个字符串，发送给服务端："</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">gets</span><span class="token punctuation">(</span>Buf<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment" spellcheck="true">/* 发送数据到服务端 */</span>
        <span class="token function">sendto</span><span class="token punctuation">(</span>ClientFd<span class="token punctuation">,</span> Buf<span class="token punctuation">,</span> <span class="token function">strlen</span><span class="token punctuation">(</span>Buf<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token keyword">struct</span> sockaddr<span class="token operator">*</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>ServerSockAddr<span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>ServerSockAddr<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">/* 接受服务端的返回数据 */</span>
        <span class="token function">recvfrom</span><span class="token punctuation">(</span>ClientFd<span class="token punctuation">,</span> Buf<span class="token punctuation">,</span> BUF_LEN<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token operator">&amp;</span>ServerAddr<span class="token punctuation">,</span> <span class="token operator">&amp;</span>addr_size<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"服务端发送过来的数据为：%s\n"</span><span class="token punctuation">,</span> Buf<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token function">memset</span><span class="token punctuation">(</span>Buf<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> BUF_LEN<span class="token punctuation">)</span><span class="token punctuation">;</span>   <span class="token comment" spellcheck="true">// 重置缓冲区</span>
    <span class="token punctuation">}</span>

    <span class="token function">close</span><span class="token punctuation">(</span>ClientFd<span class="token punctuation">)</span><span class="token punctuation">;</span>   <span class="token comment" spellcheck="true">// 关闭套接字</span>

    <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p><strong>实验现象：</strong></p>
<p>实验现象如实例1。</p>
<h2 id="五、总结"><a href="#五、总结" class="headerlink" title="五、总结"></a>五、总结</h2><p>本笔记简单介绍了一些与socket编程相关的一些知识点：IP地址，什么是端口，协议等。重点介绍了TCP、UDP通信的一些原理及其API接口的用法，并给出了windows和linux下的TCP、UDP通信实例。以上就是关于socket编程的一些总结，如有错误，欢迎指出！</p>
<hr>
<p>我的个人博客：<a href="https://www.lizhengnian.cn/">https://www.lizhengnian.cn/</a></p>
<p>我的微信公众号：嵌入式大杂烩</p>
<p>我的CSDN博客：<a href="https://blog.csdn.net/zhengnianli" target="_blank" rel="noopener">https://blog.csdn.net/zhengnianli</a></p>
<p><img src="https://s1.ax1x.com/2020/06/22/NGV7Oe.png" alt></p>

            </div>
            <hr>

            
            <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.88rem;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-large waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fa fa-close"></i></a>
            <h4 class="reward-title">欢迎关注ZhengN的微信公众号</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <!--<ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微信公众号</a></li>
                    </ul>-->
					<!--
                    <div id="alipay">
                        <img src="" class="reward-img" alt="支付宝打赏二维码">
                    </div>
					-->
                    <div id="wechat">
                        <img src="/medias/reward/wechat.jpg" class="reward-img" alt="微信公众号二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            

            <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    <div class="social-share" data-disabled="qzone" data-wechat-qrcode-helper="<p>微信里点“发现”->“扫一扫”二维码便可查看分享。</p>"></div>
    
</div>

<script src="/libs/share/js/social-share.min.js"></script>

            


        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments input[type=text],
    #vcomments input[type=email],
    #vcomments input[type=url],
    #vcomments textarea {
        box-sizing: border-box;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #42b983;
        font-weight: 500;
        text-decoration: underline;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div id="vcomments" class="card-content"></div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="/libs/valine/Valine.min.js"></script>
<script>
    new Valine({
        el: '#vcomments',
        appId: 'Vc276uuqkd8y8heuqzShe9p1-gzGzoHsz',
        appKey: 'bUwy6lANpgeVdpcQamMtC8QD',
        notify: 'false' === 'true',
        verify: 'false' === 'true',
        visitor: 'true' === 'true',
        avatar: 'mm',
        pageSize: '10',
        lang: 'zh-cn',
        placeholder: '快来快活呀！^_^'
    });
</script>
    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6 overflow-policy" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fa fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2019/07/08/ji-suan-ji-wang-luo-ji-yu-c-yu-yan-de-tian-qi-ke-hu-duan-de-shi-xian/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/21.jpg" class="responsive-img" alt="【计算机网络】基于C语言的天气客户端的实现">
                        
                        <span class="card-title">【计算机网络】基于C语言的天气客户端的实现</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            一、前言上一篇笔记分享了【socket笔记】TCP、UDP通信总结，这一篇分享一个用C语言写的、基于TCP的一个HTTP天气客户端的实现，这个一个控制台应用程序，最终的界面如下：

关于天气预报，之前我已经用STM32+ESP8266wif
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="fa fa-clock-o fa-fw icon-date"></i>2019-07-08
                        </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/计算机网络/" class="post-category" target="_blank">
                                    计算机网络
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/C语言/" target="_blank">
                        <span class="chip bg-color">C语言</span>
                    </a>
                    
                    <a href="/tags/socket/" target="_blank">
                        <span class="chip bg-color">socket</span>
                    </a>
                    
                    <a href="/tags/网络编程/" target="_blank">
                        <span class="chip bg-color">网络编程</span>
                    </a>
                    
                    <a href="/tags/TCP/" target="_blank">
                        <span class="chip bg-color">TCP</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6 overflow-policy" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fa fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2019/06/20/zuo-pin-ji-yu-stm32-de-zhi-neng-tian-qi-yu-bao-xi-tong/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/8.jpg" class="responsive-img" alt="基于STM32的智能天气预报系统">
                        
                        <span class="card-title">基于STM32的智能天气预报系统</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            1、作品介绍首先，看一下作品的演示视频：
天气预报系统
温馨提示：因为是进行人机对话演示，所以应打开音量观看哈。

这是本人的毕业设计，一个智能的天气预报系统。显示屏上显示各种天气指标及实时显示时间日期等。可以使用触摸屏输入城市名称搜索天气
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="fa fa-clock-o fa-fw icon-date"></i>2019-06-20
                            </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/嵌入式/" class="post-category" target="_blank">
                                    嵌入式
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/嵌入式/" target="_blank">
                        <span class="chip bg-color">嵌入式</span>
                    </a>
                    
                    <a href="/tags/STM32/" target="_blank">
                        <span class="chip bg-color">STM32</span>
                    </a>
                    
                    <a href="/tags/作品/" target="_blank">
                        <span class="chip bg-color">作品</span>
                    </a>
                    
                    <a href="/tags/天气预报/" target="_blank">
                        <span class="chip bg-color">天气预报</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>
</div>



    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="fa fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fa fa-list"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).slideUp(500);
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).slideDown(500);
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>
    

</main>


<footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            本站由&copy;<a href="https://zhengnianli.github.io/" target="_blank">ZhengNian</a>基于
            <a href="https://hexo.io/" target="_blank">Hexo</a> 的
            <a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">hexo-theme-matery</a>主题搭建.

            
                &nbsp;<i class="fa fa-area-chart"></i>&nbsp;站点总字数:&nbsp;
                <span class="white-color">187.2k</span>
            

            
			
                <br>
                
                <span id="busuanzi_container_site_pv">
                    <i class="fa fa-heart-o"></i>
                    本站总访问量 <span id="busuanzi_value_site_pv" class="white-color"></span>
                </span>
                
                
                <span id="busuanzi_container_site_uv">
                    <i class="fa fa-users"></i>
                    次,&nbsp;访客数 <span id="busuanzi_value_site_uv" class="white-color"></span> 人.
                </span>
                
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/zhengnianli" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fa fa-github"></i>
    </a>



    <a href="mailto:2238184039@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fa fa-envelope-open"></i>
    </a>



    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2238184039" class="tooltipped" data-tooltip="QQ联系我: 2238184039" data-position="top" data-delay="50">
        <i class="fa fa-qq"></i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fa fa-rss"></i>
    </a>
</div>
    </div>
</footer>

<div class="progress-bar"></div>


<!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fa fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字" class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
<!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fa fa-angle-up"></i>
    </a>
</div>


<script src="/libs/materialize/materialize.min.js"></script>
<script src="/libs/masonry/masonry.pkgd.min.js"></script>
<script src="/libs/aos/aos.js"></script>
<script src="/libs/scrollprogress/scrollProgress.min.js"></script>
<script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
<script src="/js/matery.js"></script>

<!-- Global site tag (gtag.js) - Google Analytics -->



    <script src="/libs/others/clicklove.js"></script>


    <script async src="/libs/others/busuanzi.pure.mini.js"></script>


</body>
</html>